from django.shortcuts import render
from rest_framework.views import APIView
from myapp.models import User
from rest_framework.response import Response
# Create your views here.

#登录
class Login(APIView):
    def post(self, request):

        # 接收参数
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)

        # 该用户存不存在
        user = User.objects.filter(username=username,password=password).first()

        if user:
            return Response({'code': 200, 'message': '登录成功！'})
        return Response({'code': 403, 'message': '该用户或者密码错误！'})

#注册
class Register(APIView):
    def post(self,request):

        # 接收参数
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)

        # 用户存不存在
        user = User.objects.filter(username=username).first()

        if user:
            return Response({'code': 403, 'message': '该用户名已经存在'})

        # 数据入库
        user = User(username=username, password=password)

        # 保存结果
        user.save()

        return Response({'code': 200, 'message': '注册成功'})